import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import Header from "../../components/Header/Header.tsx";
import { message, DatePicker, Space, TimePicker } from "antd";
import { getReadingRoomById, ReadingRoomDetail } from '../../api/readingRoomController';
import { addReadingRoomReservation } from '../../api/readingRoomReservationController';
import dayjs, { Dayjs } from 'dayjs';

interface SeatInfo {
  id: number;
  number: number;
  status: number;
}

const ReadingRoomDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [selectedSeat, setSelectedSeat] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [roomDetail, setRoomDetail] = useState<ReadingRoomDetail | null>(null);
  const [seatRows, setSeatRows] = useState<SeatInfo[][]>([]);
  const [startTime, setStartTime] = useState<Dayjs | null>(null);
  const [endTime, setEndTime] = useState<Dayjs | null>(null);
  const [sections, setSections] = useState({
    leftSection: [] as SeatInfo[][],
    middleSection: [] as SeatInfo[][],
    rightSection: [] as SeatInfo[][]
  });

  useEffect(() => {
    if (id && id !== 'undefined') {
      fetchRoomDetail(id);
    } else {
      message.error('无效的阅览室ID');
      setLoading(false);
    }
  }, [id]);

  const organizeSeatsBySection = (seats: SeatInfo[]) => {
    const leftSection: SeatInfo[][] = [];
    const middleSection: SeatInfo[][] = [];
    const rightSection: SeatInfo[][] = [];
    
    // 每行的座位数
    const leftColumns = 3;
    const middleColumns = 2;
    const rightColumns = 3;
    
    // 每行的起始索引增量
    const rowIncrement = leftColumns + middleColumns + rightColumns;
    
    // 根据总座位数计算行数
    const rowCount = Math.ceil(seats.length / rowIncrement);
    
    for (let row = 0; row < rowCount; row++) {
      const baseIndex = row * rowIncrement;
      
      // 左区域的座位 (1,2,3)
      const leftRowSeats = seats.slice(baseIndex, baseIndex + leftColumns);
      if (leftRowSeats.length > 0) {
        leftSection.push(leftRowSeats);
      }
      
      // 中区域的座位 (4,5)
      const middleRowSeats = seats.slice(
        baseIndex + leftColumns,
        baseIndex + leftColumns + middleColumns
      );
      if (middleRowSeats.length > 0) {
        middleSection.push(middleRowSeats);
      }
      
      // 右区域的座位 (6,7,8)
      const rightRowSeats = seats.slice(
        baseIndex + leftColumns + middleColumns,
        baseIndex + rowIncrement
      );
      if (rightRowSeats.length > 0) {
        rightSection.push(rightRowSeats);
      }
    }
    
    return { leftSection, middleSection, rightSection };
  };

  const fetchRoomDetail = async (roomId: string) => {
    try {
      if (!roomId || roomId === 'undefined') {
        message.error('阅览室ID不能为空');
        return;
      }
      const response = await getReadingRoomById(roomId);
      if (response.code === 200 && response.data) {
        setRoomDetail(response.data);
        const seats: SeatInfo[] = JSON.parse(response.data.seatstatus);
        const sections = organizeSeatsBySection(seats);
        setSeatRows([]); // 我们不再使用原来的seatRows
        setSections(sections);
      } else {
        message.error('获取阅览室详情失败');
      }
    } catch (error) {
      message.error('获取阅览室详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSeatClick = (seatId: number, status: number) => {
    if (status === 1) {
      setSelectedSeat(seatId);
    } else {
      message.warning('该座位已被占用');
    }
  };

  const handleReservation = async () => {
    if (!startTime || !endTime || !selectedSeat || !id) {
      message.error('请选择座位和时间');
      return;
    }

    try {
      const response = await addReadingRoomReservation({
        roomid: parseInt(id),
        seatnumber: selectedSeat,
        starttime: startTime.format('YYYY-MM-DD HH:mm:ss'),
        endtime: endTime.format('YYYY-MM-DD HH:mm:ss'),
      });

      if (response.code === 200) {
        message.success('预约成功');
        // 重新获取座位状态
        await fetchRoomDetail(id);
        // 重置选择
        setSelectedSeat(null);
        setStartTime(null);
        setEndTime(null);
      } else {
        message.error(response.message || '预约失败');
      }
    } catch (error) {
      message.error('预约失败，请重试');
    }
  };

  const renderSeatSection = (section: SeatInfo[][], title: string) => (
    <div className="flex flex-col items-center">
      <h3 className="text-lg font-semibold mb-4">{title}</h3>
      <div className="space-y-2">
        {section.map((row, rowIndex) => (
          <div key={rowIndex} className="flex space-x-2">
            {row.map((seat) => (
              <div
                key={seat.id}
                className={`
                  w-8 h-8 md:w-10 md:h-10 flex items-center justify-center rounded-lg cursor-pointer text-xs md:text-sm
                  ${seat.status === 0 ? 'bg-gray-300 cursor-not-allowed' : 'bg-green-100 hover:bg-green-200'}
                  ${selectedSeat === seat.id ? 'ring-2 ring-green-500' : ''}
                `}
                onClick={() => handleSeatClick(seat.id, seat.status)}
              >
                {seat.number}
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );

  const renderSeatingLayout = () => (
    <div className="mb-8 overflow-x-auto">
      <h2 className="text-xl md:text-2xl font-semibold mb-4 md:mb-6">座位选择</h2>
      <div className="min-w-[800px] md:min-w-0"> {/* 设置最小宽度，允许小屏滚动 */}
        <div className="flex justify-between items-stretch max-w-5xl mx-auto min-h-[300px] md:min-h-[400px]">
          {/* 左侧区域 */}
          <div className="flex-1">
            {renderSeatSection(sections.leftSection, '左区')}
          </div>
          
          {/* 走廊 */}
          <div className="mx-2 md:mx-4 flex-shrink-0 flex items-center">
            <div className="w-16 md:w-20 h-full bg-gray-100 rounded-lg flex items-center justify-center">
              <span className="text-gray-600 text-sm md:text-lg font-medium whitespace-nowrap">
                走廊通道
              </span>
            </div>
          </div>
          
          {/* 中间区域 */}
          <div className="flex-1">
            {renderSeatSection(sections.middleSection, '中区')}
          </div>
          
          {/* 走廊 */}
          <div className="mx-2 md:mx-4 flex-shrink-0 flex items-center">
            <div className="w-16 md:w-20 h-full bg-gray-100 rounded-lg flex items-center justify-center">
              <span className="text-gray-600 text-sm md:text-lg font-medium whitespace-nowrap">
                走廊通道
              </span>
            </div>
          </div>
          
          {/* 右侧区域 */}
          <div className="flex-1">
            {renderSeatSection(sections.rightSection, '右区')}
          </div>
        </div>
      </div>
    </div>
  );

  const renderReservationPanel = () => {
    if (!selectedSeat) return null;

    // 获取当前日期的开始时间和结束时间
    const today = dayjs().startOf('day');
    
    return (
      <div className="flex justify-end mt-6">
        <div className="bg-white p-4 rounded-lg shadow-md border border-gray-100 w-80">
          <p className="text-gray-600 mb-4">已选择座位：{selectedSeat}号</p>
          <div className="space-y-4 mb-4">
            <div>
              <label className="block text-sm text-gray-600 mb-2">预约时间</label>
              <Space direction="vertical" className="w-full">
                <TimePicker
                  className="w-full"
                  format="HH:mm"
                  placeholder="开始时间"
                  value={startTime}
                  onChange={(value) => {
                    if (value) {
                      const newTime = today
                        .hour(value.hour())
                        .minute(value.minute());
                      setStartTime(newTime);
                    } else {
                      setStartTime(null);
                    }
                  }}
                  minuteStep={1}  // 改为1分钟间隔
                  hideDisabledOptions
                  disabledTime={() => ({
                    disabledHours: () => [...Array(7)].map((_, i) => i),
                  })}
                />
                <TimePicker
                  className="w-full"
                  format="HH:mm"
                  placeholder="结束时间"
                  value={endTime}
                  onChange={(value) => {
                    if (value) {
                      const newTime = today
                        .hour(value.hour())
                        .minute(value.minute());
                      setEndTime(newTime);
                    } else {
                      setEndTime(null);
                    }
                  }}
                  minuteStep={1}  // 改为1分钟间隔
                  hideDisabledOptions
                  disabledTime={() => ({
                    disabledHours: () => [...Array(7)].map((_, i) => i),
                  })}
                />
              </Space>
            </div>
          </div>
          <button 
            className="w-full bg-blue-500 text-white px-6 py-2 rounded-lg hover:bg-blue-600 transition-colors"
            onClick={handleReservation}
          >
            确认预约
          </button>
        </div>
      </div>
    );
  };

  if (loading || !roomDetail) {
    return (
      <div className="h-screen flex flex-col">
        <Header />
        <div className="flex-1 flex items-center justify-center">
          <div className="text-gray-500">加载中...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen flex flex-col">
      <Header />
      <div className="flex-1 overflow-auto">
        <div className="max-w-[1400px] mx-auto px-2 md:px-4 py-4 md:py-8">
          <div className="bg-white rounded-lg shadow-lg">
            <div className="aspect-w-16 aspect-h-9">
              <img
                src={roomDetail.imageurl}
                alt={roomDetail.roomname}
                className="w-full h-[200px] md:h-[400px] object-cover"
              />
            </div>
            <div className="p-3 md:p-6">
              <h1 className="text-2xl md:text-3xl font-bold mb-2 md:mb-4">{roomDetail.roomname}</h1>
              <p className="text-gray-600 mb-4 md:mb-8">{roomDetail.description}</p>
              
              {renderSeatingLayout()}

              <div className="flex flex-wrap items-center gap-2 md:gap-4 mb-4 md:mb-6">
                <div className="flex items-center gap-2">
                  <div className="w-5 h-5 md:w-6 md:h-6 bg-green-100 rounded"></div>
                  <span className="text-sm md:text-base">空闲</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-5 h-5 md:w-6 md:h-6 bg-gray-300 rounded"></div>
                  <span className="text-sm md:text-base">已占用</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-5 h-5 md:w-6 md:h-6 bg-green-100 ring-2 ring-green-500 rounded"></div>
                  <span className="text-sm md:text-base">已选择</span>
                </div>
              </div>
              
              {renderReservationPanel()}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ReadingRoomDetail; 